﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class Faculty_AllFacultyInfo : Page//System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MaintainScrollPositionOnPostBack = true;
        if (!IsPostBack)
        {
            FillFacultyInGrid();
            ClearFieldData();
        }
    }

    #region Faculty Methods
    private DataTable FetchAllFacultyInfo()
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
        SqlConnection conn = new SqlConnection(connStr);
        SqlDataAdapter dAd = new SqlDataAdapter();
        SqlCommand dCmd = new SqlCommand();
        DataTable dTable = new DataTable();
        try
        {
            dCmd.CommandText = "SelectAllFaculties";
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Connection = conn;
            dAd.SelectCommand = dCmd;
            // now open the connection
            conn.Open();
            dAd.Fill(dTable);
            conn.Close(); // close the connection

            return dTable;
        }
        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            dCmd.Clone();
            dAd.Dispose();
            conn.Dispose();
        }
    }

    private DataTable SearchFaculties(string name)
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
        SqlConnection conn = new SqlConnection(connStr);
        SqlDataAdapter dAd = new SqlDataAdapter();
        SqlCommand dCmd = new SqlCommand();
        DataTable dTable = new DataTable();
        try
        {
            dCmd.CommandText = "FacultiesSearch";
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Connection = conn;
            SqlParameter prm = new SqlParameter("@Name", SqlDbType.VarChar, 40);
            prm.Value = name;
            dCmd.Parameters.Add(prm);
            dAd.SelectCommand = dCmd;
            // now open the connection
            conn.Open();
            dAd.Fill(dTable);
            conn.Close(); // close the connection

            return dTable;
        }
        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            dCmd.Clone();
            dAd.Dispose();
            conn.Dispose();
        }
    }

    private void InsertFacultyInfo(string name, string designation, string email, string phone, string location)
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
        int result = 0;
        SqlConnection conn = new SqlConnection(connStr);

        SqlCommand dCmd = new SqlCommand();

        try
        {
            dCmd.CommandText = "FacultyCreate"; // name of the sp
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Connection = conn;
            SqlParameter[] prms = new SqlParameter[6];
            prms[0] = new SqlParameter("@Name", SqlDbType.VarChar, 40);
            prms[0].Value = name;
            prms[1] = new SqlParameter("@Designation", SqlDbType.VarChar, 30);
            prms[1].Value = designation;
            prms[2] = new SqlParameter("@Email", SqlDbType.VarChar, 40);
            prms[2].Value = email;
            prms[3] = new SqlParameter("@Phone", SqlDbType.VarChar, 15);
            prms[3].Value = phone;
            prms[4] = new SqlParameter("@Location", SqlDbType.VarChar, 30);
            prms[4].Value = location;
            prms[5] = new SqlParameter("@FacultyAutoId", SqlDbType.Int);
            prms[5].Direction = ParameterDirection.Output;

            // add the parameters into command
            dCmd.Parameters.AddRange(prms);
            // now open the connection
            conn.Open();
            result = dCmd.ExecuteNonQuery();
            conn.Close(); // close the connection
            // write message
            if (result.Equals(0))
                Master.MasterMessageBoxText = "Couldn't insert record";
            else
                Master.MasterMessageBoxText = "Record inserted successfully with Id :" + dCmd.Parameters["@FacultyAutoId"].Value.ToString();

        }

        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            dCmd.Dispose();
            conn.Dispose();
        }
    }

    private void UpdateFacultyInfo(int facultyAutoId, string name, string designation, string email, string phone, string location)
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
        int result = 0;
        SqlConnection conn = new SqlConnection(connStr);

        SqlCommand dCmd = new SqlCommand();

        try
        {
            dCmd.CommandText = "FacultyUpdate"; // name of the sp
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Connection = conn;
            SqlParameter[] prms = new SqlParameter[6];
            prms[5] = new SqlParameter("@FacultyAutoId", SqlDbType.Int);
            prms[5].Value = facultyAutoId;
            prms[0] = new SqlParameter("@Name", SqlDbType.VarChar, 40);
            prms[0].Value = name;
            prms[1] = new SqlParameter("@Designation", SqlDbType.VarChar, 30);
            prms[1].Value = designation;
            prms[2] = new SqlParameter("@Email", SqlDbType.VarChar, 40);
            prms[2].Value = email;
            prms[3] = new SqlParameter("@Phone", SqlDbType.VarChar, 15);
            prms[3].Value = phone;
            prms[4] = new SqlParameter("@Location", SqlDbType.VarChar, 30);
            prms[4].Value = location;
 

            // add the parameters into command
            dCmd.Parameters.AddRange(prms);
            // now open the connection
            conn.Open();
            result = dCmd.ExecuteNonQuery();
            conn.Close(); // close the connection
            // write message
            if (result.Equals(0))
                Master.MasterMessageBoxText = "Couldn't able to update record";
            else
                Master.MasterMessageBoxText = "Record Updated successfully";

        }

        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            dCmd.Dispose();
            conn.Dispose();
        }
    }

    private void DeleteFaculty(int facultyAutoId)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());
        SqlCommand dCmd = new SqlCommand();
        try
        {
            conn.Open();
            dCmd.CommandText = "FacultyDelete";
            dCmd.CommandType = CommandType.StoredProcedure;
            dCmd.Parameters.Add("@FacultyAutoID", SqlDbType.Int).Value = facultyAutoId;
            dCmd.Connection = conn;
            int result = dCmd.ExecuteNonQuery();
            if (result.Equals(0))
                Master.MasterMessageBoxText = "Couldn't able to delete record";
            else
                Master.MasterMessageBoxText = "Record Deleted successfully";

        }

        catch (Exception e)
        {
            throw e;
        }

        finally
        {
            dCmd.Dispose();
            conn.Close();
            conn.Dispose();
        }

    }
    #endregion

    private void FillFacultyInGrid()
    {
        try
        {
            DataTable dTable = FetchAllFacultyInfo(); ;
            if (dTable.Rows.Count > 0)
            {
                FacultyInfoGridView.DataSource = dTable;
                FacultyInfoGridView.DataBind();
            }
            else
            {
                dTable.Rows.Add(dTable.NewRow());
                FacultyInfoGridView.DataSource = dTable;
                FacultyInfoGridView.DataBind();
                int TotalColumns = FacultyInfoGridView.Rows[0].Cells.Count;
                FacultyInfoGridView.Rows[0].Cells.Clear();
                FacultyInfoGridView.Rows[0].Cells.Add(new TableCell());
                FacultyInfoGridView.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                FacultyInfoGridView.Rows[0].Cells[0].Text = "No Record Found";
                Master.MasterMessageBoxText = Master.MasterMessageBoxText + "Operation Completed Sucessfully";
            }
        }
        catch (Exception e)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText+"--ERROR: "+ e.Message;
        }
    }

    protected void FacultyGridRowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            Master.MasterMessageBoxText = "";
            if (e.CommandName.Equals("AddNew"))
            {
                TextBox txtNewName = (TextBox)FacultyInfoGridView.FooterRow.FindControl("FacultyNameGridFooterTxtBx");
                TextBox txtNewDesignation = (TextBox)FacultyInfoGridView.FooterRow.FindControl("FacultyDesignationGridFooterTxtBx");
                TextBox txtNewEmail = (TextBox)FacultyInfoGridView.FooterRow.FindControl("FacultyEmailGridFooterTxtBx");
                TextBox txtNewPhone = (TextBox)FacultyInfoGridView.FooterRow.FindControl("FacultyPhoneGridFooterTxtBx");
                TextBox txtNewLocation = (TextBox)FacultyInfoGridView.FooterRow.FindControl("FacultyLocationGridFooterTxtBx");

                InsertFacultyInfo(txtNewName.Text, txtNewDesignation.Text, txtNewEmail.Text, txtNewPhone.Text, txtNewLocation.Text);
                FillFacultyInGrid();
            }

            if (e.CommandName.Equals("Select"))
            {

                ClearFieldData();
                //(GridViewRow)FacultyInfoGridView.SelectedRow.FindControl(
                int selectedIndex = int.Parse(e.CommandArgument.ToString());
                GridViewRow row = (GridViewRow)FacultyInfoGridView.Rows[int.Parse(e.CommandArgument.ToString())];
                if (row != null)
                {
                    FacultyAutoIdHiddenField.Value = FacultyInfoGridView.DataKeys[selectedIndex].Values[0].ToString();
                    FacultyNameTextBox.Text = ((Label)row.FindControl("FacultyNameGridViewLabel")).Text;
                    FacultyDesignationTxtBx.Text = ((Label)row.FindControl("FacultyDesignationGridViewLabel")).Text;
                    FacultyEmailTxtBox.Text = ((Label)row.FindControl("FacultyEmailGridViewLabel")).Text;
                    FacultyPhoneTxtBx.Text = ((Label)row.FindControl("FacultyPhoneGridViewLabel")).Text;
                    FacultyLocationTxtBx.Text = ((Label)row.FindControl("FacultyLocationGridViewLabel")).Text;
                    FacultyUpdatButton.Enabled = true;
                    FacultyDeleteButton.Enabled = true;
                    MaintainScrollPositionOnPostBack = false;
                }

                //FillFacultyInGrid();
            }
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }
    protected void FacultyGridEditCommand(object sender, GridViewEditEventArgs e)
    {
        FacultyInfoGridView.EditIndex = e.NewEditIndex;
        FillFacultyInGrid();
        MaintainScrollPositionOnPostBack = true;
    }
    protected void FacultyGridRowCancellingCommand(object sender, GridViewCancelEditEventArgs e)
    {
        FacultyInfoGridView.EditIndex = -1;
        FillFacultyInGrid(); 
    }
    protected void FacultyInfoGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            GridViewRow row = (GridViewRow)FacultyInfoGridView.Rows[e.RowIndex];

            TextBox txtNewName = (TextBox)row.FindControl("FacultyNameGridEditTxtBx");
            TextBox txtNewDesignation = (TextBox)row.FindControl("FacultyDesignationGridEditTxtBx");
            TextBox txtNewEmail = (TextBox)row.FindControl("FacultyEmailGridEditTxtBx");
            TextBox txtNewPhone = (TextBox)row.FindControl("FacultyPhoneGridEditTxtBx");
            TextBox txtNewLocation = (TextBox)row.FindControl("FacultyLocationGridEditTxtBx");
            int facultyAutoId = int.Parse(FacultyInfoGridView.DataKeys[e.RowIndex].Values[0].ToString());

            UpdateFacultyInfo(facultyAutoId, txtNewName.Text, txtNewDesignation.Text, txtNewEmail.Text, txtNewPhone.Text, txtNewLocation.Text);
            FacultyInfoGridView.EditIndex = -1;
            FillFacultyInGrid();
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }

    protected void FacultyInfoGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            DeleteFaculty(int.Parse(FacultyInfoGridView.DataKeys[e.RowIndex].Values[0].ToString()));
            FillFacultyInGrid();
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }

    private void ClearFieldData()
    {
        FacultyAutoIdHiddenField.Value = (-1).ToString();
        FacultyNameTextBox.Text = "";
        FacultyPhoneTxtBx.Text = "";
        FacultyDesignationTxtBx.Text = "";
        FacultyEmailTxtBox.Text = "";
        FacultyPhoneTxtBx.Text = "";
        FacultyLocationTxtBx.Text = "";
        FacultyUpdatButton.Enabled = false;
        FacultyDeleteButton.Enabled = false;

    }
    protected void FacultySearchButton_Command(object sender, CommandEventArgs e)
    {
        string searchName = FacultyNameTextBox.Text;
        try
        {
            DataTable dTable = SearchFaculties(searchName); ;
            if (dTable.Rows.Count > 0)
            {
                FacultyInfoGridView.DataSource = dTable;
                FacultyInfoGridView.DataBind();
            }
            else
            {
                dTable.Rows.Add(dTable.NewRow());
                FacultyInfoGridView.DataSource = dTable;
                FacultyInfoGridView.DataBind();
                int TotalColumns = FacultyInfoGridView.Rows[0].Cells.Count;
                FacultyInfoGridView.Rows[0].Cells.Clear();
                FacultyInfoGridView.Rows[0].Cells.Add(new TableCell());
                FacultyInfoGridView.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                FacultyInfoGridView.Rows[0].Cells[0].Text = "No Record Found";
                Master.MasterMessageBoxText = Master.MasterMessageBoxText + "Operation Completed Sucessfully";
                FacultyUpdatButton.Enabled = false;
                FacultyDeleteButton.Enabled = false;
            }
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--ERROR: " + ex.Message;
        }
    }
    protected void FacultySearchButton_Click(object sender, EventArgs e)
    {

    }
    protected void FacultyUpdatButton_Click(object sender, EventArgs e)
    {
        try
        {
            int facultyAutoId = int.Parse(FacultyAutoIdHiddenField.Value.ToString());
            string txtNewName = FacultyNameTextBox.Text;
            string txtNewDesignation = FacultyDesignationTxtBx.Text;
            string txtNewEmail = FacultyEmailTxtBox.Text;
            string txtNewPhone = FacultyPhoneTxtBx.Text;
            string txtNewLocation = FacultyLocationTxtBx.Text;

            UpdateFacultyInfo(facultyAutoId, txtNewName, txtNewDesignation, txtNewEmail, txtNewPhone, txtNewLocation);
            FillFacultyInGrid();
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }
    protected void FacultyDeleteButton_Click(object sender, EventArgs e)
    {
        try
        {
            int facId = int.Parse(FacultyAutoIdHiddenField.Value.ToString());
            if (facId != -1)
            {
                DeleteFaculty(facId);
                FillFacultyInGrid();
                ClearFieldData();
            }
            else
                Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + "Unbounded index found for delete operation";
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }
    protected void FacultyAddButton_Click(object sender, EventArgs e)
    {
        try
        {
            string txtNewName = FacultyNameTextBox.Text;
            string txtNewDesignation = FacultyDesignationTxtBx.Text;
            string txtNewEmail = FacultyEmailTxtBox.Text;
            string txtNewPhone = FacultyPhoneTxtBx.Text;
            string txtNewLocation = FacultyLocationTxtBx.Text;
            if (txtNewName != "")
            {
                InsertFacultyInfo(txtNewName, txtNewDesignation, txtNewEmail, txtNewPhone, txtNewLocation);
                FillFacultyInGrid();
            }
            else
                Master.MasterMessageBoxText = "We must have name atleast to create a faculty";
            
        }
        catch (Exception ex)
        {
            Master.MasterMessageBoxText = Master.MasterMessageBoxText + "--Error: " + ex.Message;
        }
    }
}